#监控程序  并在不存在时执行自定义行为；行为列表
#典型行为定义
import psutil,os
from jili.core.printlog import print
from jili.ibot.notic_qywx import send_msg
import subprocess
def check_proc_cmdkey(i,ss):
    rst=False
    if isinstance(i,list):
        isr=True
        for ii in i:
            if ii not in ss:
                isr=False
        if isr:
            rst=True
    else:
        if i in ss:
            rst=True
    return rst
def proc_guard(ll):
    s={}
    for proc in psutil.process_iter():
        p = proc.pid
        try:
            pp = proc
            i = pp.cmdline()
            s[p]=(pp,i)
        except psutil.AccessDenied as e:
            pass
        except Exception as e:
            print("err1", p, e)
    for l in ll:
        proc_keys = l["proc_keys"]#  main.py  [python  main.py]
        have_do_funcs=l.get("have_do_funcs",[])  #[(function,arg),(function,arg)]
        nohave_do_funcs = l.get("nohave_do_funcs", [])#[(function,arg),(function,arg)]
        ishave=False
        for pid,pp in s.items():
            r=check_proc_cmdkey(proc_keys,pp[1])
            if r:
                ishave=True
                break
        if ishave:
            for f in have_do_funcs:
                if isinstance(f[1],dict):
                    f[0](pp[0], **f[1])
                elif isinstance(f[1],list):
                    f[0](pp[0], *f[1])
                else:
                    f[0](pp[0],f[1])
        else:
            for f in nohave_do_funcs:
                if isinstance(f[1],dict):
                    f[0](**f[1])
                elif isinstance(f[1],list):
                    f[0](*f[1])
                else:
                    f[0](f[1])
def notic_msg(msg,ibotkey):
    if isinstance(ibotkey,list):
        for i in ibotkey:
            send_msg(msg, i)
    else:
        send_msg(msg,ibotkey)
def run_bat(cmd):
    os.system(cmd)
    # subprocess.call(cmd)
if __name__=="__main__":
    import os

    s = os.system("F:\qjs\mohe\startend.bat \it")